package com.xzc.shopping.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzc.shopping.common.BaseResponse;
import com.xzc.shopping.common.ResultUtils;
import com.xzc.shopping.model.vo.ProductVO;
import com.xzc.shopping.model.domain.Product;
import com.xzc.shopping.model.domain.User;
import com.xzc.shopping.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.xzc.shopping.constant.UserConstant.USER_LOGIN_STATE;

@CrossOrigin(origins = "http://localhost:3000") // 允许前端地址

@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ProductService productService;
    // 商品搜索接口
    // 后端接口添加分页参数
    @GetMapping("/search")
    public BaseResponse<List<Product>> searchProducts(
            @RequestParam String productName,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", productName);
        List<Product> products = productService.list(queryWrapper); // 改为 list() 方法
        return ResultUtils.success(products);
    }


//    @PostMapping()
// ProductController.java
@GetMapping("/{productId}")
public BaseResponse<ProductVO> getProductDetail(
        @PathVariable Integer productId,
        HttpServletRequest request
) {
    // 获取当前用户 ID（未登录则为 null）
    User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
    Integer userId = user != null ? user.getId() : null;

    // 获取商品详情（包含点赞数）
    ProductVO product = productService.getProductDetail(productId, userId);
    return ResultUtils.success(product);
}




    // 获取热门商品（带Redis缓存）
    @GetMapping("/hot")
    public BaseResponse<List<Product>> getHotProducts() {
        // 1. 尝试从Redis获取
        List<Product> hotProducts = (List<Product>) redisTemplate.opsForValue().get("hot_products");

        // 2. 缓存命中
        if (hotProducts != null && !hotProducts.isEmpty()) {
            return ResultUtils.success(hotProducts);
        }

        // 3. 缓存未命中，从数据库获取
        hotProducts = productService.getHotProductsFromDB();

        // 4. 存入Redis（设置30分钟过期时间）
        redisTemplate.opsForValue().set("hot_products",
                hotProducts,
                30,
                TimeUnit.MINUTES);

        return ResultUtils.success(hotProducts);
    }
}
